
package hk.ces.oxfam.patch.result.xml;

import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 *
 * @author ReutyCheng
 */
public class DataXMLFactory extends AbstractXMLFactory<DataXML>
{
  private static final String NODE_ROOT = "ROOT";
  private static final String NODE_METAS = "METAS";
  private static final String NODE_META = "META";
  private static final String NODE_DATA_XML = "DATA_XML";
  private static final String NODE_COLUMNS = "COLUMNS";
  private static final String NODE_COLUMN = "COLUMN";
  private static final String NODE_DATAS = "DATAS";
  private static final String NODE_DATA = "DATA";
  private static final String NODE_OBJECT = "OBJECT";

  private static final String ATTR_META_NAME = "metaName";
  private static final String ATTR_META_VALUE = "metaValue";

  protected DataXMLFactory(String fileName)
  {
    super(fileName);
  }

  protected DataXMLFactory(String folder, String fileName)
  {
    super(folder, fileName);
  }
  
  @Override
  protected Document getDocument()
  {
    Document document = addXMLStyleSheet(DocumentHelper.createDocument());
    Element rootElement = document.addElement(NODE_ROOT);

    for (DataXML dataXML : xmlItemList)
    {
      Element dataXmlElement = rootElement.addElement(NODE_DATA_XML);

      Element metasElement = dataXmlElement.addElement(NODE_METAS);
      Map<String, String> metas = dataXML.getMetas();
      for (Map.Entry<String, String> entry : metas.entrySet())
      {
        Element metaElement = metasElement.addElement(NODE_META);
        metaElement.addAttribute(ATTR_META_NAME, entry.getKey());
        metaElement.addAttribute(ATTR_META_VALUE, entry.getValue());
      }

      String[] columnNames = dataXML.getColumnNames();
      Element columnsElement = dataXmlElement.addElement(NODE_COLUMNS);
      for (String columnName : columnNames)
      {
        Element columnElement = columnsElement.addElement(NODE_COLUMN);
        columnElement.setText(columnName);
      }

      List<Object[]> resultsList = dataXML.getResultsList();
      Element datasElement = dataXmlElement.addElement(NODE_DATAS);
      for (Object[] results : resultsList)
      {
        Element dataElement = datasElement.addElement(NODE_DATA);
        for (Object result : results)
        {
          Element objectElement = dataElement.addElement(NODE_OBJECT);
          objectElement.setText(result != null ? result.toString() : "");
        }
      }
    }

    return document;
  }

  @Override
  protected String getXslFileName()
  {
    return "data-result-style.xsl";
  }
}
